package com.wx.disparent.mallparent.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;

/**
 * @author shkstart
 * @create 2019-12-18 9:39
 */
public class LoginFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest hrequest = (HttpServletRequest)servletRequest;
        System.out.println(hrequest.getRequestURI());
        HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) servletResponse);

        if(hrequest.getSession().getAttribute("userEntity")==null){
            if(hrequest.getRequestURI().indexOf("/admin")==-1
                    && hrequest.getRequestURI().indexOf("/front")==-1
                    && hrequest.getRequestURI().indexOf("/com/index")==-1
            ){
                filterChain.doFilter(servletRequest, servletResponse);
            }else if(hrequest.getRequestURI().indexOf("/admin")>=0 &&
                    (hrequest.getRequestURI().indexOf("/admin/login")!=-1
                    || hrequest.getRequestURI().indexOf("/admin/user/login")!=-1)){
                filterChain.doFilter(servletRequest, servletResponse);
            }else if(hrequest.getRequestURI().indexOf("/admin")>=0){
                wrapper.sendRedirect("/com/outLogin");
            }else if(hrequest.getRequestURI().indexOf("/front")>=0 &&
            ( hrequest.getRequestURI().indexOf("/front/user/userPath")>=0
                    || hrequest.getRequestURI().indexOf("/front/user/sureLogin")>=0
                    || hrequest.getRequestURI().indexOf("/front/user/login")>=0
                    || hrequest.getRequestURI().indexOf("/front/product/getProductInfo")>=0
                    || hrequest.getRequestURI().indexOf("/front/user/register")>=0
                    || hrequest.getRequestURI().indexOf("/front/user/forgetPassword")>=0
                    || hrequest.getRequestURI().indexOf("/front/user/sureRegister")>=0
                    || hrequest.getRequestURI().indexOf("/front/user/verification")>=0
                    || hrequest.getRequestURI().indexOf("/front/user/updatePasswordByUserId")>=0
                    || hrequest.getRequestURI().indexOf("/front/user/updatePassword")>=0
            )
            ){
                filterChain.doFilter(servletRequest, servletResponse);
            }else{
                wrapper.sendRedirect("/front/user/userPath?referId=");
            }
        }else{
            filterChain.doFilter(servletRequest, servletResponse);
        }

    }
    @Override
    public void destroy() {
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
}
